import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

public class ADServlet extends HttpServlet {
	
	protected static Logger log = Logger.getLogger(ADServlet.class);

	public static final String adPath = "/AD/";

	public static boolean isLoop = true;

	public static HashMap indexMap = new HashMap();
	
	public static String defaultFile = "default.gif";

	//	public static 
	protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1)
			throws ServletException, IOException {
		doPost(arg0, arg1);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String language = "en_GB";
		Locale loc=(Locale)request.getSession().getAttribute(org.apache.struts.Globals.LOCALE_KEY);
    	if(loc!=null)
    		language = loc.toString();
    	if(request.getParameter("type")==null){
    		PrintWriter out = response.getWriter();
    		out.println("图片路径错误 ，格式类似 /ADServlet?type=top");
    		return;
    	}
		File file = getOutFile(request.getParameter("type"),request.getParameter("indexStr"),language);
		String ext = "";
		int idx = file.getName().lastIndexOf(".");
		if (idx > 0 && idx < file.getName().length()) {
			ext = file.getName().substring(idx + 1, file.getName().length());
		}
		String contype = "image/" + ext;
		if("swf".equals(ext)){
			contype = "application/x-shockwave-flash";
		} 
		response.setHeader("Content-disposition", "filename=\"" + file.getName() + "\";");
	    response.setContentType(contype);
		response.setContentLength((int)file.length());	
		OutputStream outS = response.getOutputStream();
		outFileData( outS, file);
		outS.flush();
		outS.close();
	}

	private File getOutFile(String type,String indexStr,String language) {
		String filePath = this.getServletContext().getRealPath(adPath + type + "/"); 
		File dir = new File(filePath);
		log.debug("AD filepath====" + filePath);
		String fileName="";
		File thefile = null;
		File firstFile = null;
		if (dir.isDirectory() && dir.listFiles().length > 0) {
			if(indexStr != null){ //指定图片
				fileName = language + indexStr;
			}else{ //自动循环显示
				int index = 1;
				if (indexMap.get(type) instanceof Integer) {
					index = ((Integer) indexMap.get(type)).intValue();
				}
				fileName = language + index;
				index++;
				indexMap.put(type,new Integer(index));//递增自动循环序号
			}
			File[] files = dir.listFiles();
			for(int i=0;i<files.length;i++){
				if(files[i].getName().startsWith(language+"1"))
					firstFile = files[i];
				if(files[i].getName().startsWith(fileName))
					thefile = files[i];
			}

		}
		log.debug("try out fileName ===="+fileName);
		if(thefile == null ){
			if(indexMap.get(type) instanceof Integer && firstFile != null){//自动循环找不到文件从第一个开始
				thefile = firstFile;
				indexMap.put(type,new Integer(2));
			}else{//找不到文件输出缺省文件
				thefile = new File(this.getServletContext().getRealPath(adPath + type +"/"+ defaultFile) );				
			}
		}
		log.debug("indexMap.get ===="+indexMap.get(type));
		return thefile ;
	}
	
	
	/**
	 * 输出文件数据流
	 * @param out
	 * @param file
	 * @throws IOException
	 */
	private void outFileData(OutputStream out,File file) throws IOException  {
		log.debug(" out AD File:"+file.getPath());
		InputStream in = new FileInputStream(file);
		int b = in.read();
		while(b != -1){
			out.write(b);
			b = in.read();
		}
		out.flush();
		in.close();
	}

}
